package com.example.wificov;



import java.util.ArrayList;
import java.util.List;

import com.example.database.Point;
import com.example.database.myDBHelper;
import com.example.wificovv2.Displayband;
import com.example.wificovv2.Displaypow;
import com.example.wificovv2.Guide;
import com.example.wificovv2.MainActivity;
import com.example.wificovv2.R;
import com.example.wificovv2.SeekAp;
import com.example.wificovv2.WSTActivity;
import com.example.wificovv2.Wlanmap;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class SamplingPowPic extends Activity {
	
	myDBHelper db;
	
	WifiManager wifi;
	BroadcastReceiver receiver;
	String wifiname ; 
	float ratio1, ratio2;
	int imgwidth, imgheight;
	int pos;
	int APID, PID;
	float x = 0f;
    float y = 0f;
    String[] size;
    int mapId;
	
	private TextView bssid, dbindex;	
	private EditText typeobs, radinside, radoutside;
	private Button UpdateWifi, saveUpdateWifi, moveband, backscan;
	private ListView listpoints= null;
	
	Resources res;
	ImageView picture;
	Bitmap mutableBitmap;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_samplingpow_pic);
		db = new myDBHelper( this );
		// Lay noi dung cua ssid tu activity truoc do da chon chuyen vao Textview ssid
		ratio1 = 0f;
        ratio2 = 0f;
       		
	    res = getResources();
	    
		bssid = (TextView) findViewById(R.id.ssidmap);
		dbindex = (TextView) findViewById(R.id.dbindexmap);
		typeobs = (EditText) findViewById(R.id.typeobsmap);
		radinside = (EditText) findViewById(R.id.radinsidemap);
		radoutside = (EditText) findViewById(R.id.radoutsidemap);
		UpdateWifi = (Button) findViewById(R.id.UpdateWifi);
		saveUpdateWifi = (Button) findViewById(R.id.saveUpdateWifimap);
		moveband = (Button) findViewById(R.id.movebandmap);
		backscan = (Button) findViewById(R.id.backscanwifi);
		listpoints = (ListView) findViewById(R.id.listpoints);
		picture = (ImageView) findViewById(R.id.picview);
		
		String[] apId = {SamplingPowPic.this.getIntent().getStringExtra("arr")};
		String apid = apId[0];
		APID = Integer.parseInt(apid.toString());
		String strName = apId[1];		
		bssid.setText(strName);
	
		//Get image's size
	    BitmapFactory.Options dimensions = new BitmapFactory.Options(); 
	    dimensions.inJustDecodeBounds = true;
	    Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.newmap, dimensions);
	    imgheight = dimensions.outHeight;
	    imgwidth =  dimensions.outWidth;
		
	    final int mapId = db.MapId(APID);
		size = db.getMapsize(mapId);
		//calculate the ratios between image's size and real world distance - how many pixels per meter
		ratio1 = (float)imgwidth/(Integer.parseInt(size[0]));
		ratio2 = (float)imgheight/(Integer.parseInt(size[1]));		
		//Lấy tập điểm đã lập kế hoạch đo của AP có APID được chọn
		
	    Paint p = new Paint();
	    p.setAntiAlias(true);		
	    //cast from immutableBitmap to mutableBitmap to insert into Canvas 
	    Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.newmap );
	    mutableBitmap = bm.copy(Bitmap.Config.ARGB_8888, true);
	    Canvas c = new Canvas( mutableBitmap );
	    // Vẽ lại tập điểm lên picture
	    Point point;
	    List<Point> list = db.getPoint(APID);	    
	    for(int i=1; i< list.size(); i++){
	    	point = list.get(i);	
	    	 x = point.x;
	    	 y = point.y;
	    	 p.setColor(Color.YELLOW);
	    	c.drawCircle(x*ratio1,y*ratio2 , 10, p);
	    }
	    picture.setImageBitmap( mutableBitmap );
		    
		// Khởi tạo dữ liệu danh sách các điểm của AP cần khảo sát
		int count = db.getPlanCount(APID);		
		final String arr[] = new String[count]; 
		for(int i = 0; i < count; i++){
			arr[i] = "Possition " + i;
		} 
		String arrtemp [] = arr;
		ArrayAdapter<String>adapter=new ArrayAdapter<String>
		 (this, android.R.layout.simple_list_item_1, arrtemp);
		listpoints.setAdapter(adapter);
		listpoints.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			 public void onItemClick(
			 AdapterView<?> parent, View view, int position, long id) {
				 pos =  position;
				 
				 size = db.getMapsize(mapId);
					//calculate the ratios between image's size and real world distance - how many pixels per meter
					ratio1 = (float)imgwidth/(Integer.parseInt(size[0]));
				    ratio2 = (float)imgheight/(Integer.parseInt(size[1]));				    
				    PID = db.getPointId(APID);
				    if(pos == PID){
				    	float x ;
					    float y;
					    x = Float.parseFloat(db.getScanpos(PID, pos)[0]); // Giá trị này lấy từ database tại vị trí PID = pos
					    y = Float.parseFloat(db.getScanpos(PID, pos)[1]);					    
					    //Marker again with coordinators which equal to innitial values before
					    Paint p = new Paint();
					    p.setAntiAlias(true);
						p.setColor(Color.RED);
						Canvas cv = new Canvas(mutableBitmap);
						cv.drawCircle(x*ratio1,y*ratio2 , 3, p);
						picture.setImageBitmap(mutableBitmap);
				    }
				 }});
			
		 
		wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled() == false)
        {
            wifi.setWifiEnabled(true);
        }  
		
        registerReceiver(new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context c, Intent intent) 
            {
            	List<ScanResult> results = wifi.getScanResults();  
            	wifiname = bssid.getText().toString();
        	    for (ScanResult result : results) {
        	    	if( wifiname.equals(result.SSID)) {
        	    		int lv = result.level;
        	    		dbindex.setText("" + lv);
        	    	}
        		}
            }
        }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); 
        
				
		saveUpdateWifi.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
					db.insertSignal(APID, Integer.parseInt(dbindex.getText().toString()), 
									Integer.parseInt(typeobs.getText().toString()), 
									Integer.parseInt(radinside.getText().toString()), 
									Integer.parseInt(radoutside.getText().toString()));
					}});
		
		moveband.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(SamplingPowPic.this,Samplingbandpic.class);
				intent.putExtra("apName", APID);
				startActivity(intent);	

			}});
		
		backscan.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(SamplingPowPic.this,WSTActivity.class);
				startActivity(intent);	
			}});
		
	}
	
	/* Request updates at startup */
	@Override
	protected void onResume() {
		super.onResume();
		// locationManager.requestLocationUpdates(provider, 400, 1, this);
	}
	/* Remove the locationlistener updates when Activity is paused */
	@Override
	protected void onPause() {
		super.onPause();
		// locationManager.removeUpdates(this);
	}

//	@Override
//	public void onStop() {
//
//		wifi.End();
//	}

	public void UpdateWifiInfo(List<ScanResult> results) {
		 
//		wifi.StartScan();
		      
		    String message1 = "";
		    String message2 = "";
		    String ssidname = bssid.getText().toString();
		   
		    for (ScanResult result : results) {
		    	message1 += "\n\n" + String.format( "%s ", result.SSID);
		    	if (ssidname ==(message1) ){
			    	message2 += "\n\n" + String.format( "%d ", result.level);
			    	dbindex.setText(message2);
			    	}
		    }
	}

	public void clickHandlerForUpdateWifiButton(View v) {
		// Handle Button X here
		wifi.startScan();
	}
	
	// stop
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		super.onCreateOptionsMenu(menu);
		menu.add("Go back home screen").setIntent(
				new Intent(this, MainActivity.class));
		menu.add("Help").setIntent(new Intent(this, Guide.class));
		menu.add("Sampling power").setIntent(
				new Intent(this, SamplingPowPic.class));
		menu.add("Sampling pos and bandwidth").setIntent(
				new Intent(this, SeekAp.class));
		menu.add("View pow map").setIntent(new Intent(this, Displaypow.class));
		menu.add("View band map")
				.setIntent(new Intent(this, Displayband.class));
		menu.add("View wlan map").setIntent(new Intent(this, Wlanmap.class));
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mainscreen:
			// Xử lý tro ve man hinh chinh
			break;
		case R.id.guide:
			// xử lý xem thông huong dan
			break;
		case R.id.samplingpow:
			break;
		case R.id.samplingband:
			break;
		case R.id.powermap:
			break;
		case R.id.bandwidthmap:
			break;
		case R.id.wlanmap:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

}
